home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / lib / python2.5 / pkgutil.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2008-10-29  |  18KB  |  625 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''Utilities to support packages.'''
  5. import os
  6. import sys
  7. import imp
  8. import os.path as os
  9. from types import ModuleType
  10. __all__ = [
  11.     'get_importer',
  12.     'iter_importers',
  13.     'get_loader',
  14.     'find_loader',
  15.     'walk_packages',
  16.     'iter_modules',
  17.     'ImpImporter',
  18.     'ImpLoader',
  19.     'read_code',
  20.     'extend_path']
  21.  
  22. def read_code(stream):
  23.     import marshal as marshal
  24.     magic = stream.read(4)
  25.     if magic != imp.get_magic():
  26.         return None
  27.     
  28.     stream.read(4)
  29.     return marshal.load(stream)
  30.  
  31.  
  32. def simplegeneric(func):
  33.     '''Make a trivial single-dispatch generic function'''
  34.     registry = { }
  35.     
  36.     def wrapper(*args, **kw):
  37.         ob = args[0]
  38.         
  39.         try:
  40.             cls = ob.__class__
  41.         except AttributeError:
  42.             cls = type(ob)
  43.  
  44.         
  45.         try:
  46.             mro = cls.__mro__
  47.         except AttributeError:
  48.             
  49.             try:
  50.                 
  51.                 class cls(cls, object):
  52.                     pass
  53.  
  54.                 mro = cls.__mro__[1:]
  55.             except TypeError:
  56.                 mro = (object,)
  57.             except:
  58.                 None<EXCEPTION MATCH>TypeError
  59.             
  60.  
  61.             None<EXCEPTION MATCH>TypeError
  62.  
  63.         for t in mro:
  64.             if t in registry:
  65.                 return registry[t](*args, **kw)
  66.                 continue
  67.         else:
  68.             return func(*args, **kw)
  69.  
  70.     
  71.     try:
  72.         wrapper.__name__ = func.__name__
  73.     except (TypeError, AttributeError):
  74.         (None, None)
  75.         (None, None)
  76.     except:
  77.         (None, None)
  78.  
  79.     
  80.     def register(typ, func = ((None, None), None)):
  81.         if func is None:
  82.             return (lambda f: register(typ, f))
  83.         
  84.         registry[typ] = func
  85.         return func
  86.  
  87.     wrapper.__dict__ = func.__dict__
  88.     wrapper.__doc__ = func.__doc__
  89.     wrapper.register = register
  90.     return wrapper
  91.  
  92.  
  93. def walk_packages(path = None, prefix = '', onerror = None):
  94.     """Yields (module_loader, name, ispkg) for all modules recursively
  95.     on path, or, if path is None, all accessible modules.
  96.  
  97.     'path' should be either None or a list of paths to look for
  98.     modules in.
  99.  
  100.     'prefix' is a string to output on the front of every module name
  101.     on output.
  102.  
  103.     Note that this function must import all *packages* (NOT all
  104.     modules!) on the given path, in order to access the __path__
  105.     attribute to find submodules.
  106.  
  107.     'onerror' is a function which gets called with one argument (the
  108.     name of the package which was being imported) if any exception
  109.     occurs while trying to import a package.  If no onerror function is
  110.     supplied, ImportErrors are caught and ignored, while all other
  111.     exceptions are propagated, terminating the search.
  112.  
  113.     Examples:
  114.  
  115.     # list all modules python can access
  116.     walk_packages()
  117.  
  118.     # list all submodules of ctypes
  119.     walk_packages(ctypes.__path__, ctypes.__name__+'.')
  120.     """
  121.     
  122.     def seen(p, m = { }):
  123.         if p in m:
  124.             return True
  125.         
  126.         m[p] = True
  127.  
  128.     for importer, name, ispkg in iter_modules(path, prefix):
  129.         yield (importer, name, ispkg)
  130.         if ispkg:
  131.             
  132.             try:
  133.                 __import__(name)
  134.             except ImportError:
  135.                 if onerror is not None:
  136.                     onerror(name)
  137.                 
  138.             except Exception:
  139.                 if onerror is not None:
  140.                     onerror(name)
  141.                 else:
  142.                     raise 
  143.             except:
  144.                 onerror is not None
  145.  
  146.             if not getattr(sys.modules[name], '__path__', None):
  147.                 pass
  148.             path = []
  149.             path = _[1]
  150.             for item in walk_packages(path, name + '.', onerror):
  151.                 yield item
  152.                 []
  153.             
  154.         []
  155.     
  156.  
  157.  
  158. def iter_modules(path = None, prefix = ''):
  159.     """Yields (module_loader, name, ispkg) for all submodules on path,
  160.     or, if path is None, all top-level modules on sys.path.
  161.  
  162.     'path' should be either None or a list of paths to look for
  163.     modules in.
  164.  
  165.     'prefix' is a string to output on the front of every module name
  166.     on output.
  167.     """
  168.     if path is None:
  169.         importers = iter_importers()
  170.     else:
  171.         importers = map(get_importer, path)
  172.     yielded = { }
  173.     for i in importers:
  174.         for name, ispkg in iter_importer_modules(i, prefix):
  175.             if name not in yielded:
  176.                 yielded[name] = 1
  177.                 yield (i, name, ispkg)
  178.                 continue
  179.         
  180.     
  181.  
  182.  
  183. def iter_importer_modules(importer, prefix = ''):
  184.     if not hasattr(importer, 'iter_modules'):
  185.         return []
  186.     
  187.     return importer.iter_modules(prefix)
  188.  
  189. iter_importer_modules = simplegeneric(iter_importer_modules)
  190.  
  191. class ImpImporter:
  192.     '''PEP 302 Importer that wraps Python\'s "classic" import algorithm
  193.  
  194.     ImpImporter(dirname) produces a PEP 302 importer that searches that
  195.     directory.  ImpImporter(None) produces a PEP 302 importer that searches
  196.     the current sys.path, plus any modules that are frozen or built-in.
  197.  
  198.     Note that ImpImporter does not currently support being used by placement
  199.     on sys.meta_path.
  200.     '''
  201.     
  202.     def __init__(self, path = None):
  203.         self.path = path
  204.  
  205.     
  206.     def find_module(self, fullname, path = None):
  207.         subname = fullname.split('.')[-1]
  208.         if subname != fullname and self.path is None:
  209.             return None
  210.         
  211.         if self.path is None:
  212.             path = None
  213.         else:
  214.             path = [
  215.                 os.path.realpath(self.path)]
  216.         
  217.         try:
  218.             (file, filename, etc) = imp.find_module(subname, path)
  219.         except ImportError:
  220.             return None
  221.  
  222.         return ImpLoader(fullname, file, filename, etc)
  223.  
  224.     
  225.     def iter_modules(self, prefix = ''):
  226.         if self.path is None or not os.path.isdir(self.path):
  227.             return None
  228.         
  229.         yielded = { }
  230.         import inspect as inspect
  231.         filenames = os.listdir(self.path)
  232.         filenames.sort()
  233.         for fn in filenames:
  234.             modname = inspect.getmodulename(fn)
  235.             if modname == '__init__' or modname in yielded:
  236.                 continue
  237.             
  238.             path = os.path.join(self.path, fn)
  239.             ispkg = False
  240.             if not modname and os.path.isdir(path) and '.' not in fn:
  241.                 modname = fn
  242.                 for fn in os.listdir(path):
  243.                     subname = inspect.getmodulename(fn)
  244.                     if subname == '__init__':
  245.                         ispkg = True
  246.                         break
  247.                         continue
  248.                 
  249.             
  250.             if modname and '.' not in modname:
  251.                 yielded[modname] = 1
  252.                 yield (prefix + modname, ispkg)
  253.                 continue
  254.         
  255.  
  256.  
  257.  
  258. class ImpLoader:
  259.     '''PEP 302 Loader that wraps Python\'s "classic" import algorithm
  260.     '''
  261.     code = None
  262.     source = None
  263.     
  264.     def __init__(self, fullname, file, filename, etc):
  265.         self.file = file
  266.         self.filename = filename
  267.         self.fullname = fullname
  268.         self.etc = etc
  269.  
  270.     
  271.     def load_module(self, fullname):
  272.         self._reopen()
  273.         
  274.         try:
  275.             mod = imp.load_module(fullname, self.file, self.filename, self.etc)
  276.         finally:
  277.             if self.file:
  278.                 self.file.close()
  279.             
  280.  
  281.         return mod
  282.  
  283.     
  284.     def get_data(self, pathname):
  285.         return open(pathname, 'rb').read()
  286.  
  287.     
  288.     def _reopen(self):
  289.         if self.file and self.file.closed:
  290.             mod_type = self.etc[2]
  291.             if mod_type == imp.PY_SOURCE:
  292.                 self.file = open(self.filename, 'rU')
  293.             elif mod_type in (imp.PY_COMPILED, imp.C_EXTENSION):
  294.                 self.file = open(self.filename, 'rb')
  295.             
  296.         
  297.  
  298.     
  299.     def _fix_name(self, fullname):
  300.         if fullname is None:
  301.             fullname = self.fullname
  302.         elif fullname != self.fullname:
  303.             raise ImportError('Loader for module %s cannot handle module %s' % (self.fullname, fullname))
  304.         
  305.         return fullname
  306.  
  307.     
  308.     def is_package(self, fullname):
  309.         fullname = self._fix_name(fullname)
  310.         return self.etc[2] == imp.PKG_DIRECTORY
  311.  
  312.     
  313.     def get_code(self, fullname = None):
  314.         fullname = self._fix_name(fullname)
  315.         if self.code is None:
  316.             mod_type = self.etc[2]
  317.             if mod_type == imp.PY_SOURCE:
  318.                 source = self.get_source(fullname)
  319.                 self.code = compile(source, self.filename, 'exec')
  320.             elif mod_type == imp.PY_COMPILED:
  321.                 self._reopen()
  322.                 
  323.                 try:
  324.                     self.code = read_code(self.file)
  325.                 finally:
  326.                     self.file.close()
  327.  
  328.             elif mod_type == imp.PKG_DIRECTORY:
  329.                 self.code = self._get_delegate().get_code()
  330.             
  331.         
  332.         return self.code
  333.  
  334.     
  335.     def get_source(self, fullname = None):
  336.         fullname = self._fix_name(fullname)
  337.         if self.source is None:
  338.             mod_type = self.etc[2]
  339.             if mod_type == imp.PY_SOURCE:
  340.                 self._reopen()
  341.                 
  342.                 try:
  343.                     self.source = self.file.read()
  344.                 finally:
  345.                     self.file.close()
  346.  
  347.             elif mod_type == imp.PY_COMPILED:
  348.                 if os.path.exists(self.filename[:-1]):
  349.                     f = open(self.filename[:-1], 'rU')
  350.                     self.source = f.read()
  351.                     f.close()
  352.                 
  353.             elif mod_type == imp.PKG_DIRECTORY:
  354.                 self.source = self._get_delegate().get_source()
  355.             
  356.         
  357.         return self.source
  358.  
  359.     
  360.     def _get_delegate(self):
  361.         return ImpImporter(self.filename).find_module('__init__')
  362.  
  363.     
  364.     def get_filename(self, fullname = None):
  365.         fullname = self._fix_name(fullname)
  366.         mod_type = self.etc[2]
  367.         if self.etc[2] == imp.PKG_DIRECTORY:
  368.             return self._get_delegate().get_filename()
  369.         elif self.etc[2] in (imp.PY_SOURCE, imp.PY_COMPILED, imp.C_EXTENSION):
  370.             return self.filename
  371.         
  372.  
  373.  
  374.  
  375. try:
  376.     import zipimport
  377.     from zipimport import zipimporter
  378.     
  379.     def iter_zipimport_modules(importer, prefix = ''):
  380.         dirlist = zipimport._zip_directory_cache[importer.archive].keys()
  381.         dirlist.sort()
  382.         _prefix = importer.prefix
  383.         plen = len(_prefix)
  384.         yielded = { }
  385.         import inspect
  386.         for fn in dirlist:
  387.             if not fn.startswith(_prefix):
  388.                 continue
  389.             
  390.             fn = fn[plen:].split(os.sep)
  391.             if len(fn) == 2 and fn[1].startswith('__init__.py'):
  392.                 if fn[0] not in yielded:
  393.                     yielded[fn[0]] = 1
  394.                     yield (fn[0], True)
  395.                 
  396.             
  397.             if len(fn) != 1:
  398.                 continue
  399.             
  400.             modname = inspect.getmodulename(fn[0])
  401.             if modname == '__init__':
  402.                 continue
  403.             
  404.             if modname and '.' not in modname and modname not in yielded:
  405.                 yielded[modname] = 1
  406.                 yield (prefix + modname, False)
  407.                 continue
  408.         
  409.  
  410.     iter_importer_modules.register(zipimporter, iter_zipimport_modules)
  411. except ImportError:
  412.     pass
  413.  
  414.  
  415. def get_importer(path_item):
  416.     '''Retrieve a PEP 302 importer for the given path item
  417.  
  418.     The returned importer is cached in sys.path_importer_cache
  419.     if it was newly created by a path hook.
  420.  
  421.     If there is no importer, a wrapper around the basic import
  422.     machinery is returned. This wrapper is never inserted into
  423.     the importer cache (None is inserted instead).
  424.  
  425.     The cache (or part of it) can be cleared manually if a
  426.     rescan of sys.path_hooks is necessary.
  427.     '''
  428.     
  429.     try:
  430.         importer = sys.path_importer_cache[path_item]
  431.     except KeyError:
  432.         for path_hook in sys.path_hooks:
  433.             
  434.             try:
  435.                 importer = path_hook(path_item)
  436.             continue
  437.             except ImportError:
  438.                 continue
  439.             
  440.  
  441.         else:
  442.             importer = None
  443.         sys.path_importer_cache.setdefault(path_item, importer)
  444.     except:
  445.         None<EXCEPTION MATCH>ImportError
  446.  
  447.     if importer is None:
  448.         
  449.         try:
  450.             importer = ImpImporter(path_item)
  451.         except ImportError:
  452.             None<EXCEPTION MATCH>ImportError
  453.             None<EXCEPTION MATCH>ImportError
  454.             importer = None
  455.         except:
  456.             None<EXCEPTION MATCH>ImportError<EXCEPTION MATCH>ImportError
  457.         
  458.  
  459.     None<EXCEPTION MATCH>ImportError
  460.     return importer
  461.  
  462.  
  463. def iter_importers(fullname = ''):
  464.     '''Yield PEP 302 importers for the given module name
  465.  
  466.     If fullname contains a \'.\', the importers will be for the package
  467.     containing fullname, otherwise they will be importers for sys.meta_path,
  468.     sys.path, and Python\'s "classic" import machinery, in that order.  If
  469.     the named module is in a package, that package is imported as a side
  470.     effect of invoking this function.
  471.  
  472.     Non PEP 302 mechanisms (e.g. the Windows registry) used by the
  473.     standard import machinery to find files in alternative locations
  474.     are partially supported, but are searched AFTER sys.path. Normally,
  475.     these locations are searched BEFORE sys.path, preventing sys.path
  476.     entries from shadowing them.
  477.  
  478.     For this to cause a visible difference in behaviour, there must
  479.     be a module or package name that is accessible via both sys.path
  480.     and one of the non PEP 302 file system mechanisms. In this case,
  481.     the emulation will find the former version, while the builtin
  482.     import mechanism will find the latter.
  483.  
  484.     Items of the following types can be affected by this discrepancy:
  485.         imp.C_EXTENSION, imp.PY_SOURCE, imp.PY_COMPILED, imp.PKG_DIRECTORY
  486.     '''
  487.     if fullname.startswith('.'):
  488.         raise ImportError('Relative module names not supported')
  489.     
  490.     if '.' in fullname:
  491.         pkg = '.'.join(fullname.split('.')[:-1])
  492.         if pkg not in sys.modules:
  493.             __import__(pkg)
  494.         
  495.         if not getattr(sys.modules[pkg], '__path__', None):
  496.             pass
  497.         path = []
  498.     else:
  499.         for importer in sys.meta_path:
  500.             yield importer
  501.         
  502.         path = sys.path
  503.     for item in path:
  504.         yield get_importer(item)
  505.     
  506.     if '.' not in fullname:
  507.         yield ImpImporter()
  508.     
  509.  
  510.  
  511. def get_loader(module_or_name):
  512.     '''Get a PEP 302 "loader" object for module_or_name
  513.  
  514.     If the module or package is accessible via the normal import
  515.     mechanism, a wrapper around the relevant part of that machinery
  516.     is returned.  Returns None if the module cannot be found or imported.
  517.     If the named module is not already imported, its containing package
  518.     (if any) is imported, in order to establish the package __path__.
  519.  
  520.     This function uses iter_importers(), and is thus subject to the same
  521.     limitations regarding platform-specific special import locations such
  522.     as the Windows registry.
  523.     '''
  524.     if module_or_name in sys.modules:
  525.         module_or_name = sys.modules[module_or_name]
  526.     
  527.     if isinstance(module_or_name, ModuleType):
  528.         module = module_or_name
  529.         loader = getattr(module, '__loader__', None)
  530.         if loader is not None:
  531.             return loader
  532.         
  533.         fullname = module.__name__
  534.     else:
  535.         fullname = module_or_name
  536.     return find_loader(fullname)
  537.  
  538.  
  539. def find_loader(fullname):
  540.     '''Find a PEP 302 "loader" object for fullname
  541.  
  542.     If fullname contains dots, path must be the containing package\'s __path__.
  543.     Returns None if the module cannot be found or imported. This function uses
  544.     iter_importers(), and is thus subject to the same limitations regarding
  545.     platform-specific special import locations such as the Windows registry.
  546.     '''
  547.     for importer in iter_importers(fullname):
  548.         loader = importer.find_module(fullname)
  549.         if loader is not None:
  550.             return loader
  551.             continue
  552.     
  553.  
  554.  
  555. def extend_path(path, name):
  556.     """Extend a package's path.
  557.  
  558.     Intended use is to place the following code in a package's __init__.py:
  559.  
  560.         from pkgutil import extend_path
  561.         __path__ = extend_path(__path__, __name__)
  562.  
  563.     This will add to the package's __path__ all subdirectories of
  564.     directories on sys.path named after the package.  This is useful
  565.     if one wants to distribute different parts of a single logical
  566.     package as multiple directories.
  567.  
  568.     It also looks for *.pkg files beginning where * matches the name
  569.     argument.  This feature is similar to *.pth files (see site.py),
  570.     except that it doesn't special-case lines starting with 'import'.
  571.     A *.pkg file is trusted at face value: apart from checking for
  572.     duplicates, all entries found in a *.pkg file are added to the
  573.     path, regardless of whether they are exist the filesystem.  (This
  574.     is a feature.)
  575.  
  576.     If the input path is not a list (as is the case for frozen
  577.     packages) it is returned unchanged.  The input path is not
  578.     modified; an extended copy is returned.  Items are only appended
  579.     to the copy at the end.
  580.  
  581.     It is assumed that sys.path is a sequence.  Items of sys.path that
  582.     are not (unicode or 8-bit) strings referring to existing
  583.     directories are ignored.  Unicode items of sys.path that cause
  584.     errors when used as filenames may cause this function to raise an
  585.     exception (in line with os.path.isdir() behavior).
  586.     """
  587.     if not isinstance(path, list):
  588.         return path
  589.     
  590.     pname = os.path.join(*name.split('.'))
  591.     sname = os.extsep.join(name.split('.'))
  592.     sname_pkg = sname + os.extsep + 'pkg'
  593.     init_py = '__init__' + os.extsep + 'py'
  594.     path = path[:]
  595.     for dir in sys.path:
  596.         if not isinstance(dir, basestring) or not os.path.isdir(dir):
  597.             continue
  598.         
  599.         subdir = os.path.join(dir, pname)
  600.         initfile = os.path.join(subdir, init_py)
  601.         if subdir not in path and os.path.isfile(initfile):
  602.             path.append(subdir)
  603.         
  604.         pkgfile = os.path.join(dir, sname_pkg)
  605.         if os.path.isfile(pkgfile):
  606.             
  607.             try:
  608.                 f = open(pkgfile)
  609.             except IOError:
  610.                 msg = None
  611.                 sys.stderr.write("Can't open %s: %s\n" % (pkgfile, msg))
  612.  
  613.             for line in f:
  614.                 line = line.rstrip('\n')
  615.                 if not line or line.startswith('#'):
  616.                     continue
  617.                 
  618.                 path.append(line)
  619.             
  620.             f.close()
  621.             continue
  622.     
  623.     return path
  624.  
  625.